﻿#include "mainwindow.h"
#include <QVBoxLayout>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),workerThread(nullptr)
{
    // 创建界面元素
    startButton = new QPushButton("Start Thread", this);
    statusLabel = new QLabel("Status: Waiting", this);

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(startButton);
    layout->addWidget(statusLabel);

    QWidget *centralWidget = new QWidget(this);
    centralWidget->setLayout(layout);
    setCentralWidget(centralWidget);

    // 连接按钮点击信号到启动线程槽函数
    connect(startButton, &QPushButton::clicked, this, &MainWindow::startThread);
}

MainWindow::~MainWindow()
{
    // 确保在线程销毁前等待其结束
    if (workerThread) {
        workerThread->quit();
        workerThread->wait();
        delete workerThread;
    }
}

void MainWindow::startThread()
{
    if (workerThread) return;

    workerThread = new WorkerThread(this);

    // 连接线程的信号到处理函数
    connect(workerThread, &WorkerThread::resultReady, this, &MainWindow::handleResults);

    // 在线程结束时清理资源
    connect(workerThread, &QThread::finished, workerThread, &QObject::deleteLater);

    // 启动线程
    workerThread->start();
    statusLabel->setText("Status: Running");
}

void MainWindow::handleResults(const QString &result)
{
    statusLabel->setText("Status: " + result);
    workerThread = nullptr; // 重置线程指针
}


void WorkerThread::run()
{
    // 模拟长时间运行的任务
    QThread::sleep(5); // 休眠2秒
    emit resultReady("Finished");
}
